<?php
error_reporting(E_ALL ^ E_NOTICE);
//run on 0.17
set_time_limit(0);
date_default_timezone_set("PRC"); //timezone

$con = mysql_connect("192.168.0.17","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("faithwar", $con);
#$dateTime = date("Y-m-d",strtotime("-2 day"));
$dateTime = date("Y-m-d");
    // TRUNCATE faithwar tbheartbeat_last_temp and temp
    mysql_query("TRUNCATE TABLE faithwar.temp");
    mysql_query("TRUNCATE TABLE faithwar.tbheartbeat_last_temp");

    $deviceid_query = mysql_query("SELECT logDate,date,cities,crystal,level,deviceid FROM `tbheartbeat` WHERE date = '$dateTime' GROUP BY `deviceid`"); //id
    //$deviceid = mysql_fetch_array($deviceid_query);
    //while($deviceid[deviceid])

while($deviceid = mysql_fetch_array($deviceid_query) or die(mysql_error()))
{
	mysql_query("INSERT INTO tbheartbeat_last_temp (logDate,date,cities,crystal,level,deviceid) VALUES ('$deviceid[logDate]','$deviceid[date]','$deviceid[cities]','$deviceid[crystal]','$deviceid[level]','$deviceid[deviceid]') ");


      $user_query = mysql_query("SELECT DISTINCT `logDate` , `crystal`
		FROM `tbheartbeat`
		WHERE `deviceid` = '$deviceid[deviceid]'
		AND date = '$dateTime'"); 
      while (  $user = mysql_fetch_array($user_query)) {
      	# code...

  
}

 $firTime_query = mysql_query("SELECT DISTINCT `logDate` , `crystal` FROM `tbheartbeat` WHERE `deviceid` = '$deviceid[deviceid]' AND date = '$dateTime' group by crystal"); //id
      //$firTime = mysql_fetch_array($firTime_query);


      $secTime_query = mysql_query("SELECT DISTINCT `logDate` , `crystal` FROM `tbheartbeat` WHERE `deviceid` = '$deviceid[deviceid]' AND date = '$dateTime' group by crystal LIMIT 1,20000"); //id
      //$secTime = mysql_fetch_array($secTime_query);

      while ( $firTime = mysql_fetch_array($firTime_query) and $secTime = mysql_fetch_array($secTime_query)) {
      	# code...
      $result_query = mysql_query("SELECT (a.crystal - b.crystal) as crystal FROM tbheartbeat a, tbheartbeat b WHERE a.logDate = '$secTime[0]' AND b.logDate = '$firTime[0]'"); //id
      $result = mysql_fetch_array($result_query);


		 $sql="REPLACE INTO temp (crystal,deviceid) 
                  VALUES('$result[crystal]','$deviceid[deviceid]')";
        $query= @mysql_query($sql,$con) or die(mysql_error());  


      }

}
    

mysql_close($con);
?>